package com.chinaoct.siku.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;

import java.util.HashSet;
import java.util.Set;

public class JsonUtils {

    public static JSONObject createTemJson(String url, String title, Set<String> clients, String templateId) {
        JSONObject json =new JSONObject();
        json.put("type", "TEMPLATE");
        JSONObject body=new JSONObject();
        body.put("template_id", templateId);
        JSONArray data= new JSONArray();
        JSONObject item=new JSONObject();
        item.put("key", "title");
        item.put("value", title);
        item.put("color", "#000000");
        item.put("font_size", "12");
        item.put("text_style", "normal");
        data.add(item);
        JSONObject item1=new JSONObject();
        item1.put("key", "url");
        item1.put("value", url);
        item1.put("align", "left");
        data.add(item1);
        body.put("data", data);
        json.put("body", body);
        json.put("client_ids", clients); //usernames username client_ids userId
        JSONArray platforms=new JSONArray();
        platforms.add("ANDROID");
        platforms.add("IOS");
        json.put("platforms", platforms);
        return json;
    }

    /**
     * 将JSON字符串转换为Java对象.
     *
     * @param jsonStr
     * @param clazz   目标对象的Class类.
     * @return Java对象
     */
    @SuppressWarnings("unchecked")
    public static <T> T json2Object(String jsonStr, Class<?> clazz) {
        try {
            return (T) JSON.parseObject(jsonStr, clazz);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 将Java对象转换为json字符串.
     * 禁用循环引用检测.
     *
     * @param obj
     * @return json字符串.
     */
    public static String toJson(Object obj) {
        try {
            return JSON.toJSONString(obj, SerializerFeature.DisableCircularReferenceDetect);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        Set<String> list = new HashSet<>();
        list.add("liaojinshi");
        JSONObject jsonObject = createTemJson("https://www.baidu.com","你有一条来自xxx的待办",list,"648317b238754b6596aa1053031f2090");
        System.out.println(jsonObject.toJSONString());
    }
}
